<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\Exception;
use \think\Log;
use think\Db;

class Coupon extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $needUserLogin = ['getUserCoupon', 'pullCoupon'];

    /**
     * 获取优惠券池列表
     * @throws \think\exception\DbException
     */
    public function getCoupon()
    {
        $page = trim($this->request->request('page'));
        if (!$page) {
            $this->success('缺少重要参数', [], 201);
        }
        $couponList = Db::table('fa_coupon')
            ->where('status', 1)
            ->order('weigh desc')
            ->paginate(5, null, ['page', $page]);

        if (!$couponList) {
            $this->success('未查询到优惠券', [], 201);
        }
        $this->success('ok', ['couponList' => $couponList->items(), 'total' => $couponList->total()], 200);
    }

    /**
     * 获取用户优惠券列表
     * @throws \think\exception\DbException
     * @throws Exception
     */
    public function getUserCoupon()
    {
        if ($this->request->isPost()) {
            $data = (array)$this->_data;
            $page = trim($this->request->post('page'));
            if (!$page) {
                $this->success('缺少重要参数', [], 201);
            }

            Db::table('fa_user_coupon')
                ->where('endtime', '<=', time())
                ->update(['status' => 2]);

            $couponList = Db::table('fa_user_coupon')
                ->alias('a')
                ->field('a.*,b.*,a.id,a.status')
                ->join('fa_coupon b', 'a.coupon_id = b.id')
                ->where('user_id', $data['user_id'])
                ->order('a.status asc')
                ->order('taketime desc')
                ->paginate(5, null, ['page', $page]);


            if (!$couponList) {
                $this->success('未查询到优惠券', [], 201);
            }

            $this->success('ok', ['couponList' => $couponList->items(), 'total' => $couponList->total()], 200);
        }

    }

    /**
     * 领券接口
     *
     */
    public function pullCoupon()
    {
        if ($this->request->isPost()) {
            $data = (array)$this->_data;
            $couponId = trim($this->request->post('coupon_id'));
            if (!$couponId) {
                $this->success('缺少重要参数', [], 201);
            }
            Db::startTrans();

            try {
                $exist = Db::table('fa_user_coupon')
                    ->where('user_id', $data['user_id'])
                    ->where('coupon_id', $couponId)
                    ->find();

                if ($exist) {
                    $this->success('优惠券已拥有，切勿重复领取', [], 201);
                }
                $coupon = Db::table('fa_coupon')
                    ->where('id', $couponId)
                    ->where('max_take', '>', 'take_count')
                    ->lock(true)
                    ->find();
                if (!$coupon) {
                    Db::commit();
                    $this->success('优惠券不存在', [], 201);
                }

                Db::table('fa_coupon')
                    ->where('id', $couponId)
                    ->setInc('take_count');

                $takeTime = time();

                Db::commit();

                $result = Db::table('fa_user_coupon')
                    ->insert(['user_id' => $data['user_id'],
                        'coupon_id' => $couponId,
                        'taketime' => $takeTime,
                        'endtime' => $takeTime + $coupon['valid_days'] * 24 * 60 * 60,
                        'status' => 0]);
                if (!$result) {
                    $this->success('领取失败', [], 201);
                }
                $this->success('ok', [], 200);

            } catch (Exception $ex) {
                Db::rollback();

                Log::error($ex);
            }
        }
    }
}